const request = require('request');
const cheerio = require('cheerio');
const New = require('../models/New.js')();

class PensarContemporaneoWatch {
	
	constructor (  ) {
		this.url = 'https://www.pensarcontemporaneo.com/';
    this.websiteSlug = 'pensarcontemporaneo';
    this.tag = 'diversos';
	}

	get Url () {
		return this.url;
	}

  get Tag () {
    return this.tag;
  }

	get WebsiteSlug () {
		return this.websiteSlug;
	}

	registerLatestNovelty () {

		request(this.url, function (error, response, body) {

		  if (!error && response.statusCode == 200) {
        
		    const $ = cheerio.load(body);

		    const currentDate = new Date ();

        const href = $('.td_block_inner').find('.td-module-thumb > a').first().attr('href');
        
        request(href, function (error2, response2, body2) {

          if (!error2 && response2.statusCode == 200) {
            
            const $2 = cheerio.load(body2);
            // conteúdo da postagem
            var content = $2('.td-post-content').html();
            
            const article = {
              link: href,
              websiteSlug: this.websiteSlug,
              // data da postagem, no site...
              date: $('.td_block_inner').find('.entry-date').first().text(),
              // imagem da postagem
              thumb: $('.td_block_inner').find('img').first().attr('src'),
              // titulo da postagem
              title: $('.td_block_inner').find('.entry-title > a').first().text(),
              content: content,
              // tag da categoria
              tag: this.tag,
            }
    
            New.query
              .findAndCountAll({ where: { link: article.link } })
              .then(result => {
                if (result.count < 1) {
                  New.query.create(article);
                  console.log('[ADDED] ' + article.title + ' +')
                } else {
                  console.log('[CHECKED] ' + article.websiteSlug + ' ✓')
                }
              });

          } else {
            console.log('[ERROR] HOUVE UM ERRO NO LINK DA POSTAGEM x ')
          }

        }.bind(this));
      } else {
        console.log('[ERROR] HOUVE ALGUM ERRO x ')
      }
		}.bind(this));
	}
}

module.exports = PensarContemporaneoWatch;

